package cn.edu.zafu.bigdata.LiJuan.ch07;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class FileOperations {

    // 写入文件的方法
    public static void writeToFile(String fileName, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(fileName)))) {
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 读取文件的方法
    public static void readFromFile(String fileName) {
        File file = new File(fileName);
        try {
            if (file.exists() && !file.isDirectory()) {
                Scanner scanner = new Scanner(file);
                while (scanner.hasNextLine()) {
                    String line = scanner.nextLine();
                    System.out.println(line);
                }
                scanner.close();
            } else {
                System.out.println("File does not exist or is a directory");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 主方法，用于测试
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要写入文件的文本：");
        String text = scanner.nextLine();
        String fileName = "files/202211080104.txt";

        // 将文本写入文件
        writeToFile(fileName, text);

        // 读取并显示文件内容
        System.out.println("文件内容如下：");
        readFromFile(fileName);

        scanner.close();
    }
}
